import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hospitable_rental/models/user_info.dart';
import 'package:hospitable_rental/utils/common_toast.dart';
import 'package:hospitable_rental/utils/dio_http.dart';
import 'package:hospitable_rental/utils/store.dart';
import 'package:hospitable_rental/utils/utils.dart';

class AuthViewModel extends ChangeNotifier {
  UserInfo _userInfo = UserInfo.empty();

  UserInfo get userInfo => _userInfo;

  set userInfo(UserInfo newValue) {
    _userInfo = newValue;
    notifyListeners();
  }

  String _token = "";

  String get token => _token;

  bool get isLogin => _token.trim().isNotEmpty;

  initApp(BuildContext context) async {
    Store store = await Store.getInstance();
    String token = store.getString(StoreKey.token);
    if (!stringIsNullOrEmpty(token)) {
      _token = token;
      notifyListeners();
    }
  }

  login(BuildContext context, String username, String password) async {
    if (stringIsNullOrEmpty(username) || stringIsNullOrEmpty(password)) {
      CommonToast.showToast("用户名或密码不能为空");
      return;
    }

    CommonToast.showActivity("正在登录...");

    // 模拟网络请求
    Future.delayed(
      Duration(seconds: 3),
      () async {
        CommonToast.dismissActivity();
        _token = "12345608jfksdjfklajsdfksjd";
        notifyListeners();

        await Store.getInstance()
          ..setString(StoreKey.token, token);

        _getUserInfo(context);

        Future.delayed(
          Duration(seconds: 1),
          () => Navigator.of(context).pop(),
        );
      },
    );

    // var result = await DioHttp.of(context).post("/user/login", params: {
    //   "username": username,
    //   "password": password,
    // });

    // print(result.toString());

    // if (result.data["data"] != null && result.data["data"]["code"] == 0) {
    //   String token = result.data["data"]["token"].toString();

    //   _token = token;
    //   notifyListeners();

    //   await Store.getInstance()
    //     ..setString(StoreKey.token, token);

    //   Future.delayed(
    //     Duration(seconds: 1),
    //     () => Navigator.of(context).pop(),
    //   );
    // } else {
    //   CommonToast.showError(result.data["desc"].toString());
    // }
  }

  logout(BuildContext context) async {
    _token = "";

    Store store = await Store.getInstance();
    store.setString(StoreKey.token, "");

    _userInfo = UserInfo.empty();

    notifyListeners();

    CommonToast.showSuccess("退出登录成功");

    Navigator.of(context).pop();
  }

  _getUserInfo(BuildContext context) async {
    var result = await DioHttp.of(context).get("/user", token: token);
    var resMap = jsonDecode(result.toString());

    if (resMap["data"] != null && resMap["data"]["code"] == 0) {
      var userInfo = UserInfo.fromJson(resMap["body"]);
      _userInfo = userInfo;
      notifyListeners();
    } else {
      CommonToast.showError(resMap["desc"].toString());
    }
  }
}
